import { Color, Matrix4, Vector3, Quaternion } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';
import Poly from '../jsm/Poly.js'
import Sky from '../jsm/Sky.js'
import ShapeGeo from '../jsm/ShapeGeo.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);
    lib.clearCanvas(gl, new Color("rgba(0,0,0,1)"), 1);


    let u_m4 = gl.getUniformLocation(gl.program, 'u_m4');

    const verticeLib = [
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        -1.0, 1.0, -1.0,
        -1.0, -1.0, -1.0,
    ];

    const indices = [
        0, 1,
        1, 2,
        2, 3,
        3, 0,

        0, 5,
        1, 6,
        2, 7,
        3, 4,

        4, 5,
        5, 6,
        6, 7,
        7, 4
    ];

    const arr = [];
    indices.forEach(n => {
        const i = n * 3
        arr.push(
            verticeLib[i] / 5,
            verticeLib[i + 1] / 5,
            verticeLib[i + 2] / 5,
        )
    })

    let poly = new Poly({
        gl: gl,
        vertices: arr,
        size: 3
    })

    var viewMatrix = new getViewMatrix(
        new Vector3(0.3, 0.2, 0.5),
        new Vector3(0, 0, 0),
        new Vector3(0, 1, 0),
    );
    // var viewMatrix = new Matrix4().lookAt(
    //     new Vector3(0.3, 0.2, 0.5),
    //     new Vector3(0, 0, 0),
    //     new Vector3(0, 1, 0),
    // );

    gl.uniformMatrix4fv(u_m4, false, viewMatrix.elements);
    poly.draw(["LINES"]);


    //e视点 t目标点 u世界坐标的上方向
    function getViewMatrix(e, t, u) {
        //获取向量C 视线(由两个点获取可以获取到向量c)
        const c = new Vector3().subVectors(e, t).normalize();
        //获取向量A 视线和上方的垂线(根据视线与时间坐标的垂线可以获取到向量a)
        const a = new Vector3().crossVectors(u, c).normalize();
        //获取向量B 修正上方向至物体自身的坐标上方线(再由向量c与向量a可以获取到向c也就是自身坐标的垂线)
        const b = new Vector3().crossVectors(c, a).normalize();
        //正交旋转矩阵
        const mr = new Matrix4().set(
            ...a, 0,
            ...b, 0,
            -c.x, -c.y, -c.z, 0,
            0, 0, 0, 1
        );
        const mt = new Matrix4().set(
            1, 0, 0, -e.x,
            0, 1, 0, -e.y,
            0, 0, 1, -e.z,
            0, 0, 0, 1
        );
        return mr.multiply(mt);
    }


}